<template>
    <div class="n1">
        <div style="padding: 20px;margin-bottom: 10%">
            <el-form :model="data" :rules="mRules" ref="form" label-width="120px">
                <el-card>
                    <div slot="header" class="clearfix">
                        <span>企业信息</span>
                    </div>
                    <div>
                        <el-form-item label="企业名称" prop="name">
                            <el-input readonly v-model="data.name" style="width: 30%;" placeholder="暂无数据"/>
                        </el-form-item>
                        <el-form-item label="所属行业" prop="industryId">
                            <el-cascader style="width: 30%;"
                                         placeholder="请选择"
                                         v-model="data.industryId" :options="industryList"
                                         :props="{value:'id', label: 'name'}"
                                         :show-all-levels="false"></el-cascader>
                        </el-form-item>
                        <el-form-item label="企业规模" prop="companyScale">
                            <el-radio-group style="width: 80%" v-model="data.companyScale">
                                <el-radio v-for="companyScale in companyScaleList" :label="companyScale"
                                          :key="companyScale">
                                    {{companyScale}}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="企业类型" prop="unitType">
                            <el-checkbox-group style="width: 80%" v-model="data.unitType">
                                <el-checkbox v-for="unitType in unitTypeList" :label="unitType" :key="unitType">
                                    {{unitType}}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="企业简介" prop="companyContent">
                            <!--                            <Tinymce style="width: 80%;" v-if="tinymceActive" v-model="data.companyContent"-->
                            <!--                                     :height="521"/>-->
                            <el-input style="width: 80%" v-model="data.companyContent"
                                      maxlength="500" placeholder="请输入企业简介（最长500字）"
                                      type="textarea" :autosize="{ minRows: 10, maxRows: 20}"/>
                        </el-form-item>
                        <el-form-item label="企业简介图片" prop="companyImages">
                            <UploadImage :upload="contentImgUpload" @uploadBack="contentImgUpload.uploadBack"/>
                        </el-form-item>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="企业地址" prop="address">
                                    <el-row>
                                        <el-col :span="10">
                                            <el-cascader
                                                    style="width: 98%"
                                                    v-model="city"
                                                    placeholder="请选择城市"
                                                    :options="cityData"
                                                    expand-trigger="hover"
                                                    :props="{value:'label', label: 'label'}"
                                                    @change="handleCityChange"/>
                                        </el-col>
                                        <el-col :span="14">
                                            <el-input v-model="data.address" placeholder="详细地址"/>
                                        </el-col>
                                    </el-row>

                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="固定电话" prop="telephone">
                                    <el-input v-model="data.telephone" placeholder="请输入固定电话，区号使用-隔开，号码为7-8位"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="联系人1" prop="contactPeople1">
                                    <el-input v-model="data.contactPeople1" placeholder="暂无数据"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="联系人1职务" prop="contactPeople1Job">
                                    <el-input v-model="data.contactPeople1Job" placeholder="暂无数据"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="联系人1手机" prop="phone">
                                    <el-input v-model="data.phone" placeholder="暂无数据"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="联系人2" prop="contactPeople2">
                                    <el-input v-model="data.contactPeople2" placeholder="暂无数据"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="联系人2职务" prop="contactPeople2Job">
                                    <el-input v-model="data.contactPeople2Job" placeholder="暂无数据"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="联系人2手机" prop="phone2">
                                    <el-input v-model="data.phone2" placeholder="暂无数据"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </el-card>
                <el-card>
                    <div slot="header" class="clearfix">
                        <span>营业执照</span>
                    </div>
                    <div>
                        <el-form-item label="" prop="businessLicense">
                            <UploadImage :upload="businessLicenseImgUpload"
                                         @uploadBack="businessLicenseImgUpload.uploadBack"/>
                        </el-form-item>
                    </div>
                </el-card>
            </el-form>
        </div>
        <div class="toolbar-bottom-right">
            <el-button class="button" @click="cancel()" size="medium">取消</el-button>
            <el-button type="primary" class="button" size="medium" @click="insert()">提交</el-button>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Emit} from 'vue-property-decorator'
    import {API} from "@/core/api/API";
    import {ElForm} from "element-ui/types/form";
    import {mixins} from "vue-class-component";
    import BaseVue from "@/core/mixin/BaseVue";
    import {errorMsg, successMsg} from "@/core/utils/message";
    import $http from "@/core/utils/http";
    import {rule} from "@/core/utils/rule";
    import Kit from "@/core/mixin/Kit";
    import {getStorage, getUserInfo} from "@/core/utils/storage";
    import UploadImage from "@/components/Updalod/UploadImage.vue";
    import {copy, tree} from "@/core/utils/Utils";
    import Tinymce from "@/components/Tinymce/Tinymce.vue";
    import {cityJson} from "@/components/citySelect/cityData";

    @Component({
        name: 'CompanyInfo',
        components: {Tinymce, UploadImage},
    })
    export default class CompanyInfo extends mixins(BaseVue, Kit) {
        tinymceActive: boolean = false;

        contentImgUpload = {
            fileList: [],
            url: "/company/companyInfo/uploadFile",
            listType: "picture-card",
            maxSize: "10",
            uploadBack: this.contentImgUploadCallBack,
        };

        businessLicenseImgUpload = {
            fileList: [],
            url: "/company/companyInfo/uploadFile",
            listType: "picture-card",
            maxSize: "10",
            uploadBack: this.businessLicenseUploadCallBack,
        };

        activated() {
            this.tinymceActive = true;
        }

        deactivated() {
            this.tinymceActive = false
        }

        // 表单数据
        data: any = {
            unitType: []
        };
        // 省市区数组
        cityData: any;
        // 选择的城市
        city: any;
        // 企业类型字典
        unitTypeList: any = [];
        // 行业字典
        industryList: any = [];
        // 企业规模字典
        companyScaleList: any = [];
        //关闭时是否刷新分页
        backRefresh: boolean = false;
        mRules = {
            name: [rule.notNullBlur(), rule.length(0, 50)],
            industryId: [rule.notNullChange("请选择所属行业")],
            companyScale: [rule.notNullChange("请选择企业规模")],
            unitType: [rule.notNullChange("请选择企业类型")],
            companyContent: [rule.notNullBlur(), rule.length(0, 500)],
            address: [rule.notNullBlur("选择完成后，请输入详细地址信息"), rule.length(0, 512)],
            telephone: [rule.notNullBlur(), rule.telephone78],
            contactPeople1: [rule.notNullBlur(), rule.length(0, 20)],
            contactPeople1Job: [rule.notNullBlur(), rule.length(0, 20)],
            phone: [rule.notNullBlur(), rule.phone11],
            contactPeople2: [rule.lengthReqFalse(0, 20)],
            contactPeople2Job: [rule.lengthReqFalse(0, 20)],
            phone2: [rule.phone11_],
            businessLicense: [rule.notNullBlur("请上传营业执照"), rule.notNullChange("请上传营业执照")],
            companyImages: [rule.notNullBlur("请上传企业简介图片"), rule.notNullChange("请上传企业简介图片")],
        };

        //初始化
        async mounted() {
            // 企业类型字典数据
            this.unitTypeList = getStorage("companyType");
            // 企业规模字典数据
            this.companyScaleList = getStorage("companyScale");
            this.tinymceActive = true;
            this.cityData = cityJson;
            this.cityData = cityJson;
            this.city = ["吉林省", "长春市", "高新区"];
            await this.getIndustryTypeList();
            await this.getCompanyInfo();
            (this.$refs.form as ElForm).validate().then();
            (this.$refs.form as ElForm).validateField("businessLicense");
        }

        async cancel() {
            await this.getIndustryTypeList();
            await this.getCompanyInfo();
        }

        // 获取行业类型数据
        getIndustryTypeList() {
            return $http.post(API.industryTypeList, {}).then((res: any) => {
                if (res.success) {
                    this.industryList = tree(res.data);
                } else {
                    errorMsg("行业类型数据获取失败");
                }
                return "";
            });
        }

        // 获取企业信息
        getCompanyInfo() {
            return $http.post(API.companyInfoByUserId, {id: getUserInfo().id}).then((res1: any) => {
                if (res1.success) {
                    this.backRefresh = true;
                    this.data = res1.data;
                    // 处理企业简介图片数据
                    if (this.data.companyImages) {
                        this.data.companyImages = JSON.parse(this.data.companyImages);
                        this.contentImgUpload.fileList = copy(this.data.companyImages);
                    }
                    // 处理营业执照图片数据
                    if (this.data.businessLicense) {
                        this.data.businessLicense = JSON.parse(this.data.businessLicense);
                        this.businessLicenseImgUpload.fileList = copy(this.data.businessLicense);
                    }
                    // 处理所属行业数据组
                    if (this.data.industryId) {
                        for (let i in this.industryList) {
                            for (let j in this.industryList[i].children) {
                                if (this.data.industryId == this.industryList[i].children[j].id) {
                                    this.data.industryId = [this.industryList[i].children[j].pid, this.data.industryId];
                                    break;
                                }
                            }
                        }
                    }
                    // 处理企业类型数据
                    if (this.data.unitType) {
                        this.data.unitType = this.data.unitType.split(",");
                    } else {
                        this.data.unitType = [];
                    }
                    // 处理企业地址数据
                    if (this.data.address) {
                        let addressList = this.data.address.split("-");
                        // 截取出详细地址
                        this.data.address = addressList.pop();
                        // 剩余为省市区选择数据
                        this.city = addressList;
                    }
                } else {
                    errorMsg("数据丢失");
                }
                return "";
            })
        }

        // 保存数据
        insert() {
            (this.$refs.form as ElForm).validate().then(() => {
                let data = copy(this.data);
                data.unitType = data.unitType.join(",");
                if (typeof data.industryId == 'object') {
                    data.industryId = data.industryId[data.industryId.length - 1];
                }
                if (!data.id) {
                    data.userId = getUserInfo().id;
                    data.userAccount = getUserInfo().account;
                }
                if (data.companyImages && data.companyImages.length > 0) {
                    data.companyImages = JSON.stringify(data.companyImages);
                } else {
                    data.companyImages = "[]";
                }
                if (data.businessLicense && data.businessLicense.length > 0) {
                    data.businessLicense = JSON.stringify(data.businessLicense);
                } else {
                    data.businessLicense = "[]";
                }
                // 拼接处理地址
                data.address = this.city.join("-") + "-" + data.address;
                $http.post(API.companyInfoUpdate, data).then((res: any) => {
                    if (res.success) {
                        this.backRefresh = true;
                        successMsg("企业信息保存成功", 4000);
                        this.go("InWorkHumanInfo")
                    } else {
                        errorMsg("操作失败");
                    }
                });
            },).catch(() => {
                errorMsg("表单内容填写错误，请检查！");
            });
        }

        contentImgUploadCallBack(val: any) {
            this.data.companyImages = val.fileList;
            (this.$refs.form as ElForm).validateField("companyImages");

        }

        businessLicenseUploadCallBack(val: any) {
            this.data.businessLicense = val.fileList;
            (this.$refs.form as ElForm).validateField("businessLicense");
        }

        handleCityChange() {
            //console.log(this.city)
        }

        //关闭事件
        @Emit("close")
        close() {
            return {refresh: this.backRefresh};
        }
    }


</script>

<style scoped lang="scss">

</style>
